package com.coding.service.impl;

import com.coding.dto.RestBean;
import com.coding.entity.Conversation;
import com.coding.entity.Users;
import com.coding.entity.vo.SessionVO;
import com.coding.mapper.ConversationMapper;
import com.coding.mapper.MessageMapper;
import com.coding.mapper.UserMapper;
import com.coding.service.ConversationService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Cynicism
 * @version 1.0
 * @project DyApp
 * @description
 * @date 2024/7/3 09:51:15
 */
@Service
public class ConversationServiceImpl implements ConversationService {

    @Resource
    private ConversationMapper conversationMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private MessageMapper messageMapper;

    @Override
    public RestBean<String> insertConversation(Long userId1, Long userId2) {
        if (conversationMapper.existsByUserIds(userId1, userId2) > 0) {
            return RestBean.success("会话存在");
        }
        if (conversationMapper.insertConversation(userId1, userId2) > 0) {
            return RestBean.success();
        }
        return RestBean.failure(400, "创建会话失败");
    }

    @Override
    public RestBean<String> deleteConversation(Long userId1, Long userId2) {
        return RestBean.success();
    }

    @Override
    public RestBean<String> conversationExists(Long userId1, Long userId2) {
        if (conversationMapper.existsByUserIds(userId1, userId2) > 0) {
            return RestBean.success("会话存在");
        }
        return RestBean.success("会话不存在");
    }

    /**
     * 获取会话列表
     *
     * @param userId
     * @return
     */
    @Override
    public RestBean<List<SessionVO>> getConversationList(Long userId) {
        List<Conversation> conversations = conversationMapper.getConversationList(userId);
        if (conversations.isEmpty()){
            return RestBean.success(new ArrayList<>());
        }
        List<SessionVO> sessionVOS = new ArrayList<>();
        conversations.forEach(conversation -> {
            Users users = userMapper.getUserById(conversation.getUserId2());
            String lastMessage = messageMapper.getLastMessage(userId, conversation.getUserId2());
            if (lastMessage == null) lastMessage = "暂无消息";
            SessionVO sessionVO = new SessionVO();
            sessionVO.setReceiverId(users.getId());
            sessionVO.setUsername(users.getUserName());
            sessionVO.setAvatar(users.getAvatar());
            sessionVO.setUpdateTime(conversation.getUpdateTime());
            sessionVO.setConversationId(conversation.getConversationId());
            sessionVO.setContent(lastMessage);
            sessionVOS.add(sessionVO);
        });

        return RestBean.success(sessionVOS);
    }
}
